package com.tianshi.yingxue.controller;

import com.tianshi.yingxue.entity.Admin;
import com.tianshi.yingxue.service.impl.AdminServiceImpl;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin")
public class AdminController {

    private final AdminServiceImpl adminService;

    public AdminController(AdminServiceImpl adminService) {
        this.adminService = adminService;
    }

    @RequestMapping("/getImageCodes")
    public Map<String,String> getImageCodes() throws IOException {
        return adminService.getImageCodes();
    }
    @PostMapping("/login")
    public Map<String,String> login(@RequestBody Admin admin,String token){
        return adminService.login(admin,token);
    }
    @GetMapping("/getUserInfo")
    public Admin getUserInfo(String token){
        return adminService.getUserInfo(token);
    }
    @PostMapping("/logout")
    void logout(String token){
        System.out.println("===============>"+token);
        adminService.logout(token);
    }
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody Admin admin) {
        Map<String, Object> result = new HashMap<>();

        try {
            System.out.println("注册请求接收到的数据:");
            System.out.println("用户名: " + admin.getUsername());
            System.out.println("密码: " + admin.getPassword());
            System.out.println("验证码: " + admin.getEnCode());

            // 调用服务层完成注册
            adminService.register(admin);

            // 返回成功的JSON响应
            result.put("state", "success");
            result.put("message", "注册成功，请登录！");

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            e.printStackTrace();

            // 返回失败的JSON响应
            result.put("state", "error");
            result.put("message", "注册失败: " + e.getMessage());

            return ResponseEntity.badRequest().body(result);
        }
    }
}
